<template>
  <div class="rest-info">
    <div class="dialog">
      <el-dialog
        :visible.sync="dialogVisible"
        width="70%"
        :before-close="handleClose"
      >
        <div class="dialog-content">
          <el-form
            :validate-on-rule-change="true"
            :rules="rulesForm"
            :model="scheduleForm"
            ref="scheduleForm"
          >
            <div class="head">
              <el-form-item
                :style="{
                  display: 'flex',
                  'font-weight': 600,
                  'margin-right': '40px',
                }"
                label="作息名称："
                prop="author"
              >
                <el-input
                  v-model="scheduleForm.author"
                  placeholder="请输入作息名称"
                ></el-input>
              </el-form-item>
              <el-form-item
                prop="status"
                :style="{ display: 'flex', 'font-weight': 600 }"
                label="作息状态："
              >
                <el-select v-model="scheduleForm.status" placeholder="请选择">
                  <el-option label="启用" value="0"></el-option>
                  <el-option label="停用" value="1"></el-option>
                </el-select>
              </el-form-item>
            </div>
            <div class="normal-info">
              <div class="label">通用信息：</div>
              <div class="title">
                <el-row :gutter="20">
                  <el-col :span="3"
                    ><div class="table-label-text grid-content bg-purple">
                      序号
                    </div></el-col
                  >
                  <el-col :span="6"
                    ><div class="table-label-text grid-content bg-purple">
                      节次名称<span
                        :style="{
                          display: 'inline-block',
                          color: 'red',
                          'vertical-align': 'middle',
                        }"
                        >*</span
                      >
                    </div></el-col
                  >
                  <el-col :span="6"
                    ><div class="table-label-text grid-content bg-purple">
                      开始时间<span
                        :style="{
                          display: 'inline-block',
                          color: 'red',
                          'vertical-align': 'middle',
                        }"
                        >*</span
                      >
                    </div></el-col
                  >
                  <el-col :span="6"
                    ><div class="table-label-text grid-content bg-purple">
                      结束时间<span
                        :style="{
                          display: 'inline-block',
                          color: 'red',
                          'vertical-align': 'middle',
                        }"
                        >*</span
                      >
                    </div></el-col
                  >
                  <el-col :span="3"
                    ><div class="table-label-text grid-content bg-purple">
                      操作
                    </div></el-col
                  >
                </el-row>
              </div>

              <div
                v-for="(item, index) in scheduleForm.dialogItemList"
                :key="index + '3-n-i'"
                class="item"
              >
                <el-row :gutter="20">
                  <el-col :span="3"
                    ><div class="table-content-item grid-content bg-purple">
                      {{ index + 1 }}
                    </div></el-col
                  >
                  <el-col :span="6"
                    ><div class="table-content-item grid-content bg-purple">
                      <el-form-item
                        prop="name"
                        :rules="
                          item.name === ''
                            ? new Array({
                                required: true,
                                message: '请输入内容',
                                trigger: ['blur', 'change'],
                              })
                            : new Array({})
                        "
                      >
                        <el-input
                          v-model="item.name"
                          placeholder="请输入内容"
                          clearable
                        >
                        </el-input>
                      </el-form-item></div
                  ></el-col>
                  <el-col :span="12"
                    ><div class="table-content-item grid-content bg-purple">
                      <el-form-item
                        prop="totalTime"
                        :rules="
                          item.totalTime[0] === '' || item.totalTime[1] === ''
                            ? new Array({
                                required: true,
                                message: '请选择时间',
                                trigger: ['blur', 'change'],
                              })
                            : new Array({})
                        "
                      >
                        <el-time-picker
                          :clearable="false"
                          :style="{ width: '100%' }"
                          is-range
                          v-model="item.totalTime"
                          value-format="HH:mm"
                          format="HH:mm"
                          :picker-options="{
                            format: 'HH:mm',
                          }"
                          range-separator="至"
                          start-placeholder="开始时间"
                          end-placeholder="结束时间"
                          placeholder="选择时间范围"
                        >
                        </el-time-picker
                      ></el-form-item></div
                  ></el-col>
                  <el-col :span="3"
                    ><div class="table-content-item grid-content bg-purple">
                      <el-button
                        @click="delNormalItem(index)"
                        icon="el-icon-delete"
                      ></el-button></div
                  ></el-col>
                </el-row>
              </div>
              <el-button
                class="add-item-btn"
                @click="addNormalItem"
                type="primary"
                >+ 添加节次 (已添加{{
                  scheduleForm.dialogItemList.length
                }}节)</el-button
              >
            </div>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dealSchedule">确 定</el-button>
        </span>
      </el-dialog>
    </div>
    <el-card class="side">
      <div>
        <div class="side-top">
          <el-button
            v-if="checkAuthority('/sepScheduleInfo/add')"
            class="btn"
            size="mini"
            icon="el-icon-plus"
            @click="addScheduleHandel"
          ></el-button>
          <el-button
            v-if="checkAuthority('/sepScheduleInfo/update')"
            class="btn"
            size="mini"
            icon="el-icon-edit"
            @click="editScheduleHandel"
          ></el-button>
          <el-button
            v-if="checkAuthority('/sepScheduleInfo/delete')"
            class="btn"
            size="mini"
            icon="el-icon-delete"
            @click="deleteConfirm"
          ></el-button>
        </div>
        <div class="side-bottom">
          <el-menu
            :default-active="String(currentScheduleIndex)"
            @select="menuSelect"
            class="el-menu-vertical-demo"
          >
            <el-menu-item
              v-for="(item, index) in scheduleList"
              :key="index + '1-s-b'"
              :index="String(index)"
            >
              <div class="list-item">
                <span>{{ item.name }}</span>
                <el-switch
                  :value="item.status === '0' ? true : false"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                >
                </el-switch>
              </div>
            </el-menu-item>
          </el-menu>
        </div>
      </div>
    </el-card>

    <div class="content">
      <el-card>
        <div class="top">
          <el-row :gutter="20">
            <el-col :span="6"
              ><div class="grid-content bg-purple">
                <p>作息名称</p>
                <p class="text">
                  {{ currentSchedule ? currentSchedule.name : "" }}
                </p>
              </div></el-col
            >
            <el-col :span="6"
              ><div class="grid-content bg-purple">
                <p>作息状态</p>
                <p class="text">
                  {{
                    currentSchedule &&
                    (currentSchedule.status === "0" ? "开启" : "停用")
                  }}
                </p>
              </div></el-col
            >
            <el-col :span="6"
              ><div class="grid-content bg-purple">
                <p>节次数量</p>
                <p class="text">
                  {{ currentSchedule && currentSchedule.count }}
                </p>
              </div></el-col
            >
            <el-col :span="6"
              ><div class="grid-content bg-purple">
                <p>修改时间</p>
                <p class="text">
                  {{ currentSchedule && currentSchedule.gmtModified }}
                </p>
              </div></el-col
            >
          </el-row>
        </div>
      </el-card>
      <el-card>
        <div class="middle">
          <header class="head">
            通用信息（{{
              currentSchedule &&
              currentSchedule.list &&
              currentSchedule.list.length
            }}节）
          </header>
          <el-button
            v-if="checkAuthority('/general/update')"
            icon="el-icon-edit"
            class="btn-edit"
            @click="editScheduleHandel"
            >编辑</el-button
          >
          <div
            class="row"
            v-for="(item, index) in currentScheduleStep"
            :key="index + 'row-info'"
          >
            <div class="name">
              <span class="num box">节次</span>
              <span class="time box">时间</span>
            </div>
            <div
              v-if="currentSchedule && currentSchedule.list"
              :style="{ display: 'flex' }"
            >
              <div
                v-for="(item1, index) in item"
                :key="index + '2-r-d'"
                class="data"
              >
                <span class="num box">{{ item1.name }}</span>
                <span class="time box">{{
                  item1.startTime + " - " + item1.endTime
                }}</span>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import {
  getScheduleList,
  addSchedule,
  editSchedule,
  deleteSchedule,
  updateStatus
} from './js/restInfo'
import { checkAuthority } from '@/utils/btnPermission' // 页面按钮权限

export default {
  name: 'restInfo',
  data () {
    return {
      rulesForm: {
        author: [
          {
            required: true,
            message: '请输入作息名称',
            trigger: ['blur', 'change']
          },
          {
            validator: this.validatorName,
            trigger: ['blur', 'change']
          }
        ],
        status: [
          { required: true, message: '请选择', trigger: ['blur', 'change'] }
        ]
        // name: [{ required: true, message: '请输入内容', trigger: ['blur', 'change'] }],
        // totalTime: [{ required: true, message: '请选择时间', trigger: ['blur', 'change'] }]
      },
      value: true,
      dialogVisible: false,
      scheduleForm: {
        author: '',
        status: '',
        dialogItemList: [
          {
            totalTime: ['06:00', '23:00'],
            name: '',
            type: '100'
          }
        ]
      },
      dialogType: '',

      currentScheduleIndex: 0,
      scheduleList: []
    }
  },
  computed: {
    currentSchedule: function () {
      return this.scheduleList[this.currentScheduleIndex]
    },

    currentScheduleStep: function () {
      if (
        this.scheduleList[this.currentScheduleIndex] &&
        this.scheduleList[this.currentScheduleIndex].list
      ) {
        let result = []
        for (
          var i = 0;
          i < this.scheduleList[this.currentScheduleIndex].list.length;
          i += 6
        ) {
          result.push(
            this.scheduleList[this.currentScheduleIndex].list.slice(i, i + 6)
          )
        }

        return result
      } else {
        return []
      }
    }
  },
  mounted () {
    this.dealScheduleList({})
  },

  watch: {
    scheduleList: {
      handler () {
        // console.log('深度监听：', val)
      },
      deep: true
    }
  },

  methods: {
    checkAuthority,
    validatorName (rule, value, callback) {
      let byteLength = value.replace(/[^\x00-\xff]/g, "**").length; // eslint-disable-line
      if (byteLength > 30) {
        callback(new Error('长度不能大于30字符'))
      } else {
        callback()
      }
    },

    async dealScheduleList (params) {
      const { code, msg, data } = await getScheduleList(params)
      if (code === 0) {
        this.currentScheduleIndex = data.findIndex(
          (item) => item.status === '0'
        )
        this.scheduleList = [...data]
      } else {
        this.$message.warning(msg)
      }
    },

    async dealSchedule () {
      this.$refs['scheduleForm'].validate(async (valid) => {
        if (valid) {
          let params = {
            count: this.scheduleForm.dialogItemList.length,
            list: this.scheduleForm.dialogItemList.map((item) => {
              return {
                endTime: item.totalTime[1],
                name: item.name,
                startTime: item.totalTime[0],
                type: '100'
              }
            }),
            name: this.scheduleForm.author,
            status: this.scheduleForm.status
          }
          let tip = ''
          let code
          let msg
          if (this.dialogType === 'add') {
            let res = await addSchedule(params)
            code = res.code
            msg = res.msg

            tip = '添加成功'
          } else if (this.dialogType === 'edit') {
            params.id = this.currentSchedule.id

            let res = await editSchedule(params)
            code = res.code
            msg = res.msg
            tip = '编辑成功'
          }
          if (code === 0) {
            this.$message.success(tip)
            this.dialogVisible = false
            this.dealScheduleList({})
          } else {
            this.$message.warning(msg)
          }
        } else {
          // console.log('error submit!!')
          return false
        }
      })
    },

    async delSchedule () {
      let params = this.currentSchedule.id
      const { code, msg } = await deleteSchedule(params)
      if (code === 0) {
        this.dealScheduleList({})
        this.$message.success('删除成功')
      } else {
        this.$message.warning(msg)
      }
    },

    addScheduleHandel () {
      this.dialogVisible = true
      this.dialogType = 'add'
      this.scheduleForm = {
        author: '',
        status: '',
        dialogItemList: [
          {
            totalTime: ['06:00', '23:00'],
            name: '',
            type: ''
          }
        ]
      }
    },

    deleteConfirm () {
      this.$confirm('确认删除？')
        .then((_) => {
          this.delSchedule()
        })
        .catch((_) => {})
    },

    editScheduleHandel () {
      this.dialogVisible = true
      this.dialogType = 'edit'

      this.scheduleForm = {
        author: this.currentSchedule.name,
        status: this.currentSchedule.status,
        dialogItemList: this.currentSchedule.list.map((item) => {
          return {
            totalTime: [item.startTime, item.endTime],
            name: item.name,
            type: item.type
          }
        })
      }
    },

    addNormalItem () {
      this.scheduleForm.dialogItemList.push({
        totalTime: ['06:00', '23:00'],
        name: '',
        type: '100'
      })
    },
    delNormalItem (index) {
      this.$confirm('确认删除？')
        .then((_) => {
          this.scheduleForm.dialogItemList.splice(index, 1)
        })
        .catch((_) => {})
    },

    async menuSelect (index) {
      const { code, msg } = await updateStatus({
        id: this.scheduleList[index].id
      })
      if (code === 0) {
        index = Number(index)
        this.currentScheduleIndex = index
        this.scheduleList.forEach((item, i) => {
          if (Number(index) === i) {
            item.status = '0'
          } else {
            item.status = '1'
          }
        })
      } else {
        this.$message.warning(msg)
      }
    },

    handleClose (done) {
      done()
      // this.$confirm('确认关闭？')
      //   .then((_) => {
      //     done()
      //   })
      //   .catch((_) => {})
    },
    onSubmit () {
      // console.log('submit!')
    }
  }
}
</script>

<style scoped lang="scss">
.rest-info {
  widows: 100%;
  display: flex;
  .dialog {
    .dialog-content {
      .head {
        display: flex;
      }
      .normal-info {
        .label {
          font-size: 14px;
          font-weight: 600;
          margin-bottom: 10px;
        }
        .title {
          .table-label-text {
            text-align: center;
          }
        }
        .item {
          .table-content-item {
            height: 60px;
            display: flex;
            justify-content: center;
            align-items: center;
          }
        }

        .add-item-btn {
          display: block;
          margin: 20px auto;
        }
      }
    }
  }
  .side {
    margin-right: 20px;
    flex: 0.2 0 auto;
    .side-top {
      .btn {
        width: 16px;
        height: 16px;
        border: none;
        padding: 0;
      }
    }
    .side-bottom {
      padding: 20px 0 0;
      .list-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
    }
  }
  .content {
    flex: 0.8;
    .top {
      .grid-content {
        margin-right: 30px;
        .text {
          padding: 10px 0 0;
          font-size: 14px;
          font-weight: 600;
        }
      }
    }
    .middle {
      .btn-edit {
        border: none;
        font-size: 13px;
        padding: 0;
        margin: 0 0 10px;
      }
      .head {
        margin: 0 0 10px;
        font-size: 14px;
        font-weight: 600;
      }
      .row {
        display: flex;
        .box {
          display: flex;
          justify-content: center;
          align-items: center;
          background: #e8e8e8db;
          border: 1px solid #999;
        }
        .name {
          .num {
            width: 60px;
            height: 30px;
          }
          .time {
            width: 60px;
            height: 50px;
          }
        }
        .data {
          .num {
            width: 90px;
            height: 30px;
          }
          .time {
            width: 90px;
            height: 50px;
            background: white;
          }
        }
      }
    }
  }
}
</style>
